<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <span>修改密码</span>
      </div>
    </template>
    <el-form
      :model="dataForm"
      label-width="100px"
      :rules="dataFormRules"
      ref="queryFormRef"
      label-position="right"
    >
      <el-form-item label="旧密码:" prop="oldpassword">
        <el-input
          show-password
          v-model="dataForm.oldpassword"
          type="password"
        />
      </el-form-item>
      <el-form-item label="新密码:" prop="newpassword">
        <el-input
          show-password
          v-model="dataForm.newpassword"
          type="password"
        />
      </el-form-item>
      <el-form-item label="确认密码:" prop="checkpassword">
        <el-input
          show-password
          v-model="dataForm.checkpassword"
          type="password"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">确认</el-button>
        <el-button @click="cancel" type="danger">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { updatePsw } from '@/api/user'
import { useRouter } from 'vue-router'

const dataForm = ref({
  oldpassword: '',
  newpassword: '',
  checkpassword: '',
})

const dataFormRules = reactive({
  oldpassword: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
  newpassword: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
  checkpassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validatePasswords, trigger: 'blur' },
  ],
})

function validatePasswords(rule: any, value: any, callback: any) {
  if (value === '') {
    callback(new Error('请确认密码'))
  } else if (value !== dataForm.value.newpassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const userpsw = ref('')
let $router = useRouter()
const submit = async () => {
  if (dataForm.value.oldpassword !== userpsw.value) {
    ElMessage({
      type: 'error',
      message: '原密码输入错误',
    })
  } else {
    try {
      const postData = {
        password: dataForm.value.newpassword,
        id: JSON.parse(localStorage.getItem('robotData') as string).id as any,
      }
      const res = await updatePsw(postData)
      if (res.flag) {
        ElMessage({ type: 'success', message: '更新成功' })
        $router.replace({ path: '/login' })
      }
    } catch {}
  }
}

const cancel = () => {
  window.history.back()
}

onMounted(() => {
  if (!!localStorage.getItem('robotData')) {
    const obj = JSON.parse(localStorage.getItem('robotData') as any)
    userpsw.value = obj.password
  }
})
</script>
<style scoped></style>
